#pragma once

// #include <sys/select.h>
// #include <sys/poll.h>
#include <sys/epoll.h>
#include <memory>
#include "Socket.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"
#include "Common.hpp"

using namespace LogModule;
using namespace SocketModule;

class EpollServer
{
    static const int size = 64;
    static const int defaultfd = -1;

public:
    EpollServer(const InetAddr &addr)
        : _listensock(std::make_unique<TCPSocket>(addr, Type::SERVER)),
          _isrunning(false),
          _epfd(defaultfd)
    {
        // 1.创建epoll模型
        _epfd = epoll_create(256);
        if (_epfd < 0)
        {
            LOG(LogLevel::FATAL) << "epoll_create error";
            exit(EPOLL_CREATE_ERR);
        }

        // 2.将listensockfd添加到epoll红黑树中
        struct epoll_event events;
        events.data.fd = _listensock->Fd();
        events.events = EPOLLIN;
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, _listensock->Fd(), &events);
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_ctl add listensockfd error";
            exit(1);
        }
    }

    void Start()
    {
        _isrunning = true;
        struct epoll_event evts[size];
        while (_isrunning)
        {
            // 不能直接accept，等待的事情交给poll
            int timeout = -1;
            // epoll，等待多个读fd
            int n = epoll_wait(_epfd, evts, size, timeout);
            switch (n)
            {
            case 0:
                LOG(LogLevel::INFO) << "epoll超时了";
                break;
            case -1:
                LOG(LogLevel::ERROR) << "epoll error";
                break;
            default:
                Dispatch(evts, n); // 等待成功，将等待结果rfds处理
                break;
            }
        }
        _isrunning = false;
    }

    // 派遣任务
    void Dispatch(struct epoll_event *evts, int n)
    {
        for (int pos = 0; pos < n; pos++)
        {
            // 1.取出读就绪的fd，epoll_wait拿到的都是就绪的
            if (evts[pos].events & EPOLLIN)
            {
                // listenfd读就绪
                if (evts[pos].data.fd == _listensock->Fd())
                    Accept();
                // 普通sockfd读就绪
                else
                    Recv(evts, pos);
            }
        }
    }

    // 获取连接
    void Accept()
    {
        InetAddr addr;
        int sockfd = _listensock->Accept(&addr); // 一定不会阻塞，因为读事件已经就绪
        if (sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "accept error";
            exit(ACCEPT_ERR);
        }
        else
        {
            // 连接获取成功，直接添加epoll
            struct epoll_event events;
            events.data.fd = sockfd;
            events.events = EPOLLIN;
            epoll_ctl(_epfd, EPOLL_CTL_ADD, sockfd, &events);
        }
    }

    void Recv(struct epoll_event *evts, int pos)
    {
        int sockfd = evts[pos].data.fd;
        char buff[1024];
        ssize_t n = read(sockfd, buff, sizeof(buff) - 1);
        if (n < 0)
        {
            LOG(LogLevel::WARNING) << "read error";
            // 1.删除epoll红黑树中sockfd节点，删除只能删除合法的，应该先移除在关闭
            epoll_ctl(_epfd, EPOLL_CTL_DEL, sockfd, nullptr);

            // 2.关闭连接sockfd，防止文件描述符泄漏
            close(sockfd);
        }
        else if (n == 0)
        {
            LOG(LogLevel::INFO) << "client exit, remove fd from epoll's rb_tree: " << sockfd;
            // 1.删除epoll红黑树中sockfd节点，删除只能删除合法的，应该先移除在关闭
            epoll_ctl(_epfd, EPOLL_CTL_DEL, sockfd, nullptr);

            // 2.关闭连接sockfd，防止文件描述符泄漏
            close(sockfd);
        }
        else
        {
            // 读到了数据
            buff[n] = 0;
            std::cout << "client says@ " << buff;
        }
    }

    void Stop()
    {
        _isrunning = false;
    }
    ~EpollServer()
    {
        _listensock->Close();
    }

private:
    std::unique_ptr<Socket> _listensock;
    bool _isrunning;

    int _epfd; // epoll模型的fd
};